package com.lagou.penglei.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;

/**
 * @author ascetic
 * @version 1.0
 * @ClassName DbChangeListener
 * @Description TODO
 * @date 2020-07-04 15:41
 */
@Component
public class DbChangeListener {


    @Autowired
    private CuratorFramework zkClinet;

    @Autowired
    private DataSource dataSource;

    @PostConstruct
    public void init() throws Exception {
        NodeCache cache = new NodeCache(zkClinet, "/dataBase");
        cache.getListenable().addListener(new NodeCacheListener() {
            @Override
            public void nodeChanged() throws Exception {
                String cdate = new String(cache.getCurrentData().getData());

                String [] args = cdate.split("\\|");

                DruidDataSource changeDate = new DruidDataSource();
                changeDate.setDriverClassName(args[0].split("=")[1]);
                changeDate.setUrl(args[1].split("=")[1]);
                changeDate.setUsername(args[2].split("=")[1]);
                changeDate.setPassword(args[3].split("=")[1]);

                dataSource = changeDate;
                System.out.println(dataSource);
            }
        });
        cache.start();
    }
}